<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;
use tools\jwt\Token;

class Base extends Controller
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        //允许的源域名
        header("Access-Control-Allow-Origin: *");
        //允许的请求头信息
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        //允许的请求类型
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');

        //接受token
        $token = input('token');
        if (empty($token)) {
            //token为空时，返回错误信息
            $this->error('缺少token参数', 'admin/login/login');
        }

        //验证token是否正确
        $userId = Token::verifyToken($token);
        if (!$userId) {
            //token不正确
            $this->error('token失效', 'admin/login/login');
        }

        // 取出用户权限
        // 1. session
        $userNode = Session::get('userNode');
        // 将权限地址拼接 //路径：控制器名/方法名   node_controller/node_action  => [goods/,goods/create,goods/update]
        $nodeData = ['index/index'];

        if (!empty($userNode)) {
            foreach ($userNode as $node) {
                foreach ($node['child'] as $child) {
                    if (isset($child['node_controller']) && isset($child['node_action'])) {
                        $nodeData[] = strtolower($child['node_controller']) . '/' . strtolower($child['node_action']);
                    }
                }
            }
        }

        $controller = \request()->controller();
        $action = \request()->action();
        $path = strtolower($controller) . '/' . strtolower($action);
//        print_r($path);
//        print_r($nodeData);die;
        //比较 用户权限和当前地址
        if (!in_array($path,$nodeData)) {
            //没有权限
            $this->error('无权限，请联系管理员...','admin/index/index');
        }

    }
}
